let config = require('./lib/config');
let errorListen = require('./lib/error');
let sequelize = require('sequelize');
let taf = require('@taf/taf-rpc');
let log = require('./lib/log');
global.TafAlarm = require('@taf/taf-alarm');
// let fileLocker = require('./lib/fakeFileLock');


let SynObj = require('./jce/SynchronousProxy').News;
let DbProxyObj = require('./jce/DBProxyProxy').Base;

let GetConDif = require('./server/GetConfDif');
let DifInfo2Sql = require('./server/DifInfo2sql');
let SynDbInfo = require('./server/SynDbInfo');

errorListen.listen();

config.loadConfig('Synchronous.conf', 'c')
    .then((configs) => {
        global.configs = configs;
        return initDb(global.configs);
    })
    .then(() => {
        return initPrx(global.configs);
    })
    .then(() => {
        return startServer(global.configs);

    })
    .catch(err => {
        console.log('error when start servers : ' + err);
        process.exit(0);
    });

//初始化数据库
function initDb(configs) {
    return new Promise((resolve, reject) => {
        global.mysqlDb = {};
        global.mysqlDb.realDb = new sequelize(
            configs.mysqlDbInfo.realMysql.db_name,
            configs.mysqlDbInfo.realMysql.user,
            configs.mysqlDbInfo.realMysql.password, {
                'host': configs.mysqlDbInfo.realMysql.host,
                'port': configs.mysqlDbInfo.realMysql.port,
                'dialect': 'mysql',
                'pool': {
                    max: 100,
                    min: 1,
                    idle: 500
                },
                timezone: '+08:00'
            });
        global.mysqlDb.testDb = new sequelize(configs.mysqlDbInfo.testMysql.db_name, configs.mysqlDbInfo.testMysql.user, configs.mysqlDbInfo.testMysql.password, {
            'host': configs.mysqlDbInfo.testMysql.host,
            'port': configs.mysqlDbInfo.testMysql.port,
            'dialect': 'mysql',
            'pool': {
                max: 100,
                min: 1,
                idle: 500
            },
            timezone: '+08:00'
        });

        if (global.mysqlDb.realDb && global.mysqlDb.testDb) {
            resolve();
        } else {
            reject('init mysql false');
        }
    });
}

//初始化接口
function initPrx(configs) {
    global.tafPrx = {};
    return new Promise((resolve, reject) => {
        //global.tafPrx.oracle = require('@up/oracle-client')('news', 'upapp', {strPrx: configs.obj.OracleServerObj});
        global.tafPrx.dbProxy = taf.client.stringToProxy(DbProxyObj.DBProxyProxy, global.configs.obj.DBProxyObj);
        global.tafPrx.dbProxy.setTimeout(30 * 1000);
        resolve();
    });
}

function startServer(configs) {

    /**worker状态打印**/
    log.status.debug(`{servantProcessNum num}|${process.env.PROCESS_NUM}`);
    log.status.debug(`{currentWorkerIndex index}|${process.env.PROCESS_INDEX}`);

    if (process.env.TAF_CONFIG && (!process.env.PROCESS_NUM || !process.env.PROCESS_INDEX)) {
        process.exit(0);
    }

    /**start server**/
    if (!process.env.TAF_CONFIG || process.env.PROCESS_INDEX == 0) {
        global.getConDif=new GetConDif();
        global.difInfo2Sql = new DifInfo2Sql();
        global.synDbInfo = new SynDbInfo();

        // /** test **/
        // const startId = 0
        // const endId = 0
        // /**
        //  * @type {News.GetRecordDifReq|News.GetRecordDifReq}
        //  * syn startId endId
        //  * syn startId
        //  */
        // let GetRecordDifReq = new SynObj.GetRecordDifReq();
        // GetRecordDifReq.difType = 0;
        //
        // //获取difInfo - all
        // global.getConDif.getConInfo(GetRecordDifReq)
        //     .then(res => {
        //         let SynReq = new SynObj.SynReq();
        //         SynReq.startId=startId;
        //         return Promise.resolve(global.synDbInfo.start(res,SynReq));
        //     })
        //     .then(res=>{
        //         let a ;
        //     })
        //     .catch(err => {
        //         let a;
        //     });

    }
    ;

    /**start tafServer**/
    if (process.env.TAF_CONFIG) {
        let svr = new taf.server();
        svr.initialize(process.env.TAF_CONFIG, function (server) {
            server.addServant(CTestImp.CTestImp, server.Application + "." + server.ServerName + ".CTestObj");
            svr.start();
        });
    }
    console.log('start server finish');
}
